package com.example.jf.jfapp.widget.bottomtab;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import java.util.ArrayList;


public class BottomLayout extends LinearLayout {

    public BottomLayout(Context context) {
        super(context);
    }

    public BottomLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public BottomLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 当前View只负责底部导航的东西
     * 如果界面进行切换，外界做了什么改变，我们不需要知道
     * 因为外界的改变是不固定，所以必须得由外界决定，那么我们只需要通知外界
     * 告诉它，我们进行切换了
     * @param viewPager
     * @param tabBeens
     */
    public void setViewPager(ViewPager viewPager, final ArrayList<TabBean> tabBeens){
        this.viewPager = viewPager;

        initTabView(tabBeens);

        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < getChildCount(); i++) {
                    getChildAt(i).setSelected(position == i ? true : false);
                    if(mBottomPageChangeListener!=null){
                        mBottomPageChangeListener.onPageSelected(position);
                        //我们正常开发，都是调用系统的api，将这个思路反过来，让系统去调我们的api，那么就是回调
                    }
                }
            }
        });
    }

    public interface BottomPageChangeListener{
        void onPageSelected(int position);
    }

    BottomPageChangeListener mBottomPageChangeListener;

    public void setBottomPageChangeListener(BottomPageChangeListener bottomPageChangeListener) {
        this.mBottomPageChangeListener = bottomPageChangeListener;
    }

    ViewPager viewPager;
    public void initTabView(ArrayList<TabBean> tabBeens){
        for (int i = 0; i < viewPager.getAdapter().getCount(); i++) {
            TabView tabView = new TabView(getContext(),tabBeens.get(i).getTitle(), tabBeens.get(i).getChoooseResId(),tabBeens.get(i).getNormalResId());
            LayoutParams layoutParams = new LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.weight = 1;
            tabView.setLayoutParams(layoutParams);


            final int finalI = i;
            tabView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    viewPager.setCurrentItem(finalI);
                }
            });

            if(i == 0){
                tabView.setSelected(true);
            }
            addView(tabView);
        }

    }

}
